Checked.opCmp

Compares this against rhs for ordering. If Hook defines hookOpCmp, the function forwards to hook.hookOpCmp(get, rhs). Otherwise, the result of the built-in comparison operation is returned.

If U is also an instance of Checked, both hooks (left- and right-hand side) are introspected for the method hookOpCmp. If both define it, priority is given to the left-hand side.

  1. auto opCmp(const U rhs)
    struct Checked(T, Hook = Abort)
    opCmp
    (
    U
    this _
    )
    (
    const U rhs
    )
    if (
    isIntegral!U ||
    isFloatingPoint!U
    ||
    is(U == bool)
    )
    if (
    isIntegral!T ||
    is(T == Checked!(U, H),
    U
    H
    )
    )
  2. auto opCmp(Checked!(U, Hook1) rhs)

Examples

1 static struct MyHook
2 {
3     static bool thereWereErrors;
4     static int hookOpCmp(L, R)(L lhs, R rhs)
5     {
6         static if (isUnsigned!L && !isUnsigned!R)
7         {
8             if (rhs < 0 && rhs >= lhs)
9                 thereWereErrors = true;
10         }
11         else static if (isUnsigned!R && !isUnsigned!L)
12         {
13             if (lhs < 0 && lhs >= rhs)
14                 thereWereErrors = true;
15         }
16         // Preserve built-in behavior.
17         return lhs < rhs ? -1 : lhs > rhs;
18     }
19 }
20 auto a = checked!MyHook(-42);
21 assert(a > uint(42));
22 assert(MyHook.thereWereErrors);
23 static struct MyHook2
24 {
25     static int hookOpCmp(L, R)(L lhs, R rhs)
26     {
27         // Default behavior
28         return lhs < rhs ? -1 : lhs > rhs;
29     }
30 }
31 MyHook.thereWereErrors = false;
32 assert(Checked!(uint, MyHook2)(uint(-42)) <= a);
33 //assert(Checked!(uint, MyHook2)(uint(-42)) >= a);
34 // Hook on left hand side takes precedence, so no errors
35 assert(!MyHook.thereWereErrors);
36 assert(a <= Checked!(uint, MyHook2)(uint(-42)));
37 assert(MyHook.thereWereErrors);

Meta